<template>
  <div class="app-container">
    <!-- 搜索模块 -->
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px">
      <el-form-item label="区域" prop="region">
        <el-select v-model="queryParams.region" filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in region"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="凹陷" prop="dent">
        <el-select v-model="queryParams.dent" filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in dent"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="井号" prop="wellname">
        <el-select v-model="queryParams.wellname" filterable placeholder="请选择">
          <el-option
            v-for="(item,index) in wellname"
            :key="index"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" format="yyyy-MM-dd" placeholder="选择日期"
                        style="width: 240px" value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="年度" prop="scene">
        <el-input v-model="queryParams.year" placeholder="年度" size="small" style="width: 240px"  />
      </el-form-item> -->
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 图标权限模块 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button icon="el-icon-s-order" plain size="mini" type="primary"
                   @click="handleModelwell"
        >井数据模板下载
        </el-button>
        <el-button icon="el-icon-s-order" plain size="mini" type="primary"
                   @click="handleModelcost"
        >费用模板下载
        </el-button>
        <el-button v-hasPermi="['admin:approve:ledger:add:post']" icon="el-icon-upload" plain size="mini" type="primary"
                   @click="handleAdd"
        >数据导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-upload" plain size="mini" type="primary" @click="handleAddCost">费用导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['admin:approve:form:add:post']" icon="el-icon-plus" plain size="mini" type="primary"
                   @click="handleAddData"
        >数据录入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-download" plain size="mini" type="primary" @click="downloadData">数据下载
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-copy-document" plain size="mini" type="primary" @click="handleCopy">批量复制
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['admin:approve:form:delete:{id}:delete']" :disabled="multiple" icon="el-icon-delete" plain
                   size="mini" type="danger" @click="handleDelete"
        >批量删除
        </el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList"/>
    </el-row>
    <!-- 展示模块 -->
    <el-table border v-loading="loading" :data="ledgerList" stripe @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="70"/>
      <el-table-column align="center" label="区域" prop="region"></el-table-column>
      <el-table-column align="center" label="凹陷" prop="dent"></el-table-column>
      <el-table-column align="center" label="井号" prop="wellname"></el-table-column>
      <el-table-column align="center" label="井别" prop="well_type"></el-table-column>
      <el-table-column align="center" label="井深" prop="welldepth"></el-table-column>
      <!-- <el-table-column prop="xmz" label="项目组" align="center"> </el-table-column> -->
      <el-table-column align="center" label="钻机" prop="rigname"></el-table-column>
      <!-- <el-table-column prop="rigmodel" label="钻机型号" align="center"></el-table-column> -->
      <el-table-column align="center" label="是否核销" prop="ishx"></el-table-column>
      <el-table-column align="center" label="开钻日期" prop="kzrq"></el-table-column>
      <!-- <el-table-column prop="kz" label="开钻" align="center"></el-table-column> -->
      <el-table-column align="center" label="完钻日期" prop="wzrq"></el-table-column>
      <!-- <el-table-column prop="wz" label="完钻" align="center"></el-table-column> -->
      <el-table-column align="center" label="完井日期" prop="wjrq"></el-table-column>
      <!-- <el-table-column prop="wj" label="完井" align="center"></el-table-column> -->
      <el-table-column align="center" label="累计完成进尺" prop="ljwcjc"></el-table-column>
      <el-table-column align="center" label="设计进尺" prop="sjjc"></el-table-column>
      <el-table-column align="center" label="统计年度" prop="year"></el-table-column>
      <el-table-column align="center" label="统计年度完成进尺" prop="tjndwcjc"></el-table-column>
      <el-table-column align="center" label="上一年度完成进尺" prop="syndwcjc"></el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="180">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" size="mini" type="text"
                     @click="handleDetail(scope.row)"
          >修改
          </el-button>
          <el-button v-hasPermi="['admin:approve:form:delete:{id}:delete']" icon="el-icon-delete" size="mini"
                     type="text"
                     @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
                @pagination="getList"
    />
    <!-- 文件上传|修改 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="this.form.id == undefined" label="数据导入" prop="path">
          <el-upload ref="uploadRef" :action="uploadUrl" :data="uploadData" :headers="headers" :http-request="chunkUpload"
                     :on-error="onError" :on-success="handleSuccess" accept=".xlsx, .xls, .csv" class="upload-demo" drag
                     name="file"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx/csv文件，且列名不能重复</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--费用导入-->
    <el-dialog :close-on-click-modal="false" :title="titleCost" :visible.sync="openCost" append-to-body width="500px">
      <el-form ref="formCost" :model="formCost" :rules="rulesCost" label-width="80px">
        <el-form-item v-if="this.form.id == undefined" label="费用导入" prop="path">
          <el-upload ref="uploadRef" :action="uploadUrl" :data="uploadData" :headers="headers" :http-request="chunkUpload"
                     :on-error="onError" :on-success="handleSuccess" accept=".xlsx, .xls, .csv" class="upload-demo" drag
                     name="file"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">只能上传xls/xlsx/csv文件，且列名不能重复</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCostForm">确 定</el-button>
        <el-button @click="openCost=false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="sjlrTitle" :visible.sync="addDataVisible" append-to-body
               width="1200px"
    >
      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane label="井基本信息" name="wellinfo">
          <el-form ref="lrForm" :inline="true" :model="lrForm" :rules="lrRules" label-width="120px">
            <el-form-item label="区域" prop="region">
              <el-input v-model="lrForm.region" placeholder="区域" style="width: 240px"/>
            </el-form-item>
            <el-form-item label="凹陷" prop="dent">
              <el-input v-model="lrForm.dent" placeholder="凹陷" style="width: 240px"/>
            </el-form-item>
            <el-form-item label="井号" prop="wellname">
              <el-input v-model="lrForm.wellname" placeholder="井号" style="width: 240px"/>
            </el-form-item>
            <el-form-item label="井类型" prop="well_type">
              <el-select v-model="lrForm.well_type" placeholder="井类型" size="small" style="width: 240px">
                <el-option key="预探井" label="预探井" value="预探井"/>
                <el-option key="评价井" label="评价井" value="评价井"/>
              </el-select>
            </el-form-item>
            <el-form-item label="井深" prop="welldepth">
              <el-input v-model="lrForm.welldepth" placeholder="井深" style="width: 240px" type="number"/>
            </el-form-item>
            <el-form-item label="项目组" prop="xmz">
              <el-input v-model="lrForm.xmz" placeholder="项目组" style="width: 240px"/>
            </el-form-item>
            <el-form-item label="钻机" prop="rigname">
              <el-input v-model="lrForm.rigname" placeholder="钻机" style="width: 240px"/>
            </el-form-item>
            <el-form-item label="是否核销" prop="ishx">
              <el-select v-model="lrForm.ishx" placeholder="是否核销" size="small" style="width: 240px">
                <el-option key="拟核销" label="拟核销" value="拟核销"/>
                <el-option key="是" label="是" value="是"/>
                <el-option key="否" label="否" value="否"/>
              </el-select>
            </el-form-item>
            <el-form-item label="开钻日期" prop="kzrq">
              <el-date-picker v-model="lrForm.kzrq" format="yyyy.MM.dd" placeholder="选择日期" style="width: 240px"
                              type="date" value-format="yyyy.MM.dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="完钻日期" prop="wzrq">
              <el-date-picker v-model="lrForm.wzrq" format="yyyy.MM.dd" placeholder="选择日期" style="width: 240px"
                              type="date" value-format="yyyy.MM.dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="完井日期" prop="wjrq">
              <el-date-picker v-model="lrForm.wjrq" format="yyyy.MM.dd" placeholder="选择日期" style="width: 240px"
                              type="date" value-format="yyyy.MM.dd"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="统计年度" prop="year">
              <el-input v-model="lrForm.year" placeholder="统计年度" style="width: 240px" type="number"/>
            </el-form-item>
            <el-form-item label="累计完成进尺" prop="ljwcjc">
              <el-input v-model="lrForm.ljwcjc" placeholder="累计完成进尺" style="width: 240px" type="number"/>
            </el-form-item>
            <el-form-item label="设计进尺" prop="sjjc">
              <el-input v-model="lrForm.sjjc" placeholder="设计进尺" style="width: 240px" type="number"/>
            </el-form-item>
            <el-form-item label="上年度完成进尺" prop="syndwcjc">
              <el-input v-model="lrForm.syndwcjc" placeholder="上一年度完成进尺" style="width: 240px" type="number"/>
            </el-form-item>
            <el-form-item v-show="lrForm.id!=''" label="钻测录合同小计" prop="zclhtxj">
              <el-input v-model="lrForm.zclhtxj" disabled placeholder="钻测录合同小计" style="width: 240px"/>
            </el-form-item>
            <el-form-item v-show="lrForm.id!=''" label="研究费及管理费小计" prop="yjfjglfxj">
              <el-input v-model="lrForm.yjfjglfxj" disabled placeholder="研究费及管理费小计" style="width: 240px"/>
            </el-form-item>
            <el-form-item v-show="lrForm.id!=''" label="钻井小计" prop="zjxj">
              <el-input v-model="lrForm.zjxj" disabled placeholder="钻井小计" style="width: 240px"/>
            </el-form-item>
            <el-form-item v-show="lrForm.id!=''" label="试油小计" prop="syxj">
              <el-input v-model="lrForm.syxj" disabled placeholder="试油小计" style="width: 240px"/>
            </el-form-item>
          </el-form>

          <div class="dialog-footer" style="padding-left:900px">
            <el-button type="primary" @click="addLedgerClick">确 定</el-button>
            <el-button @click="addDataVisible=false">取 消</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="费用明细" name="costinfo">
          <el-tabs v-model="costdetail">
            <el-tab-pane label="钻井费用录入" name="zj">
              <el-table :key="Math.random()" v-loading="loading"
                        :data="costdetailListzj.filter(data => !search || data.cost_name.toLowerCase().includes(search.toLowerCase()))"
              >
                <el-table-column align="center" label="费用名称" prop="cost_name" width="120">
                </el-table-column>
                <el-table-column align="center" label="费用类型" prop="cost_type" width="150">
                </el-table-column>
                <el-table-column align="center" label="实际费用" prop="real_cost" width="150">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.real_cost" placeholder="实际费用" type="number"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="已结费用" prop="check_cost" width="150">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.check_cost" placeholder="已结费用" type="number"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="公司名称" prop="company" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.company" placeholder="公司名称"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="备注" prop="remark" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注" type="number"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" class-name="small-padding fixed-width">
                  <template slot="header" slot-scope="scope">
                    <el-input
                      v-model="search"
                      placeholder="输入关键字搜索"
                      size="mini"
                    />
                  </template>
                  <template slot-scope="scope">
                    <el-button icon="el-icon-plus" size="mini" type="text"
                               @click="handleCostAdd(scope.row)"
                    >添加
                    </el-button>
                    <!-- <el-button  size="mini" type="text" icon="el-icon-delete"
                      @click="handleCostDelete(scope.row)">删除</el-button> -->
                  </template>
                </el-table-column>
              </el-table>
              <div class="dialog-footer" style="padding-left:800px">
                <el-button type="primary" @click="editCostClick">确 定</el-button>
                <el-button @click="addDataVisible=false">取 消</el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="试油费用录入" name="sy">
              <el-table :key="Math.random()" v-loading="loading"
                        :data="costdetailListsy.filter(data => !search || data.cost_name.toLowerCase().includes(search.toLowerCase()))"
              >
                <el-table-column align="center" label="费用名称" prop="cost_name" width="120">
                </el-table-column>
                <el-table-column align="center" label="费用类型" prop="cost_type" width="150">
                </el-table-column>
                <el-table-column align="center" label="实际费用" prop="real_cost" width="150">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.real_cost" placeholder="实际费用" type="number"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="已结费用" prop="check_cost" width="150">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.check_cost" placeholder="已结费用" type="number"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="公司名称" prop="company" width="120">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.company" placeholder="公司名称"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="备注" prop="remark" width="100">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注" type="number"/>
                  </template>
                </el-table-column>
                <el-table-column align="center" class-name="small-padding fixed-width">
                  <template slot="header" slot-scope="scope">
                    <el-input
                      v-model="search"
                      placeholder="输入关键字搜索"
                      size="mini"
                    />
                  </template>
                  <template slot-scope="scope">
                    <el-button icon="el-icon-plus" size="mini" type="text"
                               @click="handleCostAdd(scope.row)"
                    >添加
                    </el-button>
                    <!-- <el-button  size="mini" type="text" icon="el-icon-delete"
                      @click="handleCostDelete(scope.row)">删除</el-button> -->
                  </template>
                </el-table-column>
              </el-table>
              <div class="dialog-footer" style="padding-left:800px">
                <el-button type="primary" @click="editCostClick">确 定</el-button>
                <el-button @click="addDataVisible=false">取 消</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="addCostdetail" append-to-body title="费用添加"
               width="500px"
    >
      <el-form :inline="true" :model="addCostForm" label-width="68px">
        <el-form-item label="实际费用" prop="real_cost">
          <el-input v-model="addCostForm.real_cost" placeholder="实际费用" style="width: 240px" type="number"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addCostClick">确 定</el-button>
          <el-button @click="addCostdetail=false">取 消</el-button>
        </el-form-item>
        <!-- <el-form-item label="日期" prop="createTime">
          <el-date-picker v-model="addCostForm.createTime" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 240px" ></el-date-picker>
        </el-form-item> -->
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  addLedger,
  addType,
  addTypeCost,
  copyLedgerData,
  dataEche,
  deepCopy,
  delCostType,
  delType,
  downloadLedger,
  editCost,
  editLedger,
  editType,
  listTypeAll,
  listTypeDetailByTime,
  getDictList
} from "@/api/vadmin/budget/ledger/ledgerapi";

import chunkUpload from "@/utils/chunkUpload";
import { getToken } from "@/utils/auth";
import { Decrypt } from "@/utils/AesHmacMD5";
import * as XLSX from "xlsx";

export default {
  name: "ledger",
  data() {
    return {
      // 遮罩层
      loading: true,
      search: "",
      addCostForm: { real_cost: 10000, createTime: "" },
      activeName: "wellinfo",
      costdetail: "zj",
      editCostdetail: null,
      addCostdetail: false,
      regionOptions0: [],
      regionOptions1: [],
      regionOptions1_: [],
      rigOptions: [],
      costdetailList: [],
      costdetailListzj: [],
      costdetailListsy: [],
      addDataVisible: false,
      isfylr: false,
      selectLedger: {
        regionname: "",
        wellname: "",
        well_type: "",
        welldepth: "",
        group: "",
        rig: "",
        rigmodel: "",
        ishx: "",
        wjzt: ""
      },
      ledgerDict: {
        "region": "区域",
        "dent": "凹陷",
        xmz: "项目组",
        rig: "钻机",
        wellname: "井号",
        welldepth: "井深",
        ishx: "是否核销",
        wjzt: "完井状态",
        kzrq: "开钻日期",
        wzrq: "完钻日期",
        wjrq: "完井日期",
        wj: "完井",
        ljwcjc: "累计完成进尺",
        sjjc: "设计进尺",
        year: "统计年度",
        tjndwcjc: "统计年度完成进尺",
        syndwcjc: "上一年度完成进尺"
      },
      // 选中数组
      ids: [],
      lrForm: {
        id: "",
        region: "",
        dent: "",
        wellname: "",
        well_type: "预探井",
        welldepth: "",
        xmz: "",
        rigname: "",
        rigmodel: "",
        ishx: "是",
        kzrq: "",
        wzrq: "",
        wjrq: "",
        year: 2024,
        ljwcjc: "",
        sjjc: "",
        syndwcjc: ""
      },
      valNames: [],
      companyOptions: [],
      sjlrTitle: "数据录入",
      costOptions: [{ value: 0, label: "钻测录合同" }, { value: 1, label: "钻井" }, {
        value: 2,
        label: "研究费及管理费"
      }, { value: 3, label: "试油" }],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 批复表格数据
      ledgerList: [],
      // 弹出层标题
      title: "",
      titleCost: "",
      // 是否显示弹出层
      open: false,
      openCost: false,
      openCostdetail: false,
      // 场景数据字典
      sceneOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,  // 当前页数
        pageSize: 10,  // 每页显示几个
        wellname: "", year: "2024", region: "", dent: "", well_type: "", rigname: "", createTime: ""
      },
      // 表单参数
      form: {},
      formCost: {},
      // 表单校验
      rules: {
        path: [
          { required: true, validator: this.validatorPath(), trigger: "blur" }
        ]
      },
      lrRules: {
        regionid: [{ required: true, message: "区域不能为空", trigger: "change" }],
        wellname: [{ required: true, message: "井号不能为空", trigger: "blur" }],
        well_type: [{ required: true, message: "井号不能为空", trigger: "change" }],
        welldepth: [{ required: true, message: "井号不能为空", trigger: "blur" }],
        rig_id: [{ required: true, message: "钻机不能为空", trigger: "change" }],
        ljwcjc: [{ required: true, message: "累计完成进尺不能为空", trigger: "blur" }],
        sjjc: [{ required: true, message: "设计进尺不能为空", trigger: "blur" }],
        syndwcjc: [{ required: true, message: "上一年度完成进尺", trigger: "blur" }]
        // wjrq:[{ type: 'date', required: true, message: '请选择日期', trigger: 'change'  }],
        // kzrq:[{ type: 'date', required: true, message: '请选择日期', trigger: 'change'  }],
        // wzrq:[{ type: 'date', required: true, message: '请选择日期', trigger: 'change'  }],
      },
      rulesCost: {},
      chunkUpload: chunkUpload, // 文件上传
      uploadUrl: process.env.VUE_APP_BASE_API + "/admin/system/upload_fileM/", //文件上传的路径
      uploadData: {},
      headers: {
        Authorization: "Bearer " + getToken()
      },

      //11.7修改 新增凹陷数组 区域数组 井号数组
      dent:[], //凹陷
      region:[], //区域
      wellname:[] //井号
    };
  },
  created() {
    let currentDate = new Date();
    let year = currentDate.getFullYear();
    let month = currentDate.getMonth() + 1;  // 注意月份从0开始，需要加1
    let day = currentDate.getDate();
    this.queryParams.createTime = year + "-" + month + "-" + day;
    this.getList();
    this.getDict();
    // this.addCostForm.createTime=year + "-" + month + "-" + day;
  },
  methods: {
    //查询所有的区域 凹陷 井号
    getDict() {
      console.log('查询所有');
      getDictList(this.addDateRange('aa')).then(response => {
        let res = JSON.parse(Decrypt(response.data));
        //区域数组
        this.region = res.region.flat();
        //凹陷数组
        this.dent = res.dent.flat();
        //井号数组
        this.wellname = res.wellname.flat();

      })
    },

    validatorPath() {
      return (rule, value, callback) => {
        if (this.form.id == undefined && !value) {
          return callback(new Error("数据文件不能为空"));
        } else {
          callback();
        }
      };
    },
    /** 查询数字台账列表 */
    getList() {
      this.loading = true;
      var _this = this;
      console.log(this.queryParams,this.dateRange);
      listTypeAll(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data));
        this.ledgerList = resData.results;
        this.total = resData.count;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        scene: undefined,
        path: undefined
      };
      this.formCost = {
        path: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 文件上传按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "文件导入";
    },
    handleAddData() {
      this.addDataVisible = true;
      this.isfylr = false;
      this.lrForm.id == "";
      this.sjlrTitle = "数据录入";
      this.lrForm = {
        id: "",
        regionid: "",
        wellname: "",
        well_type: "预探井",
        welldepth: "",
        xmz: "",
        rig_id: "",
        ishx: "是",
        kzrq: "",
        wzrq: "",
        wjrq: "",
        year: 2024,
        ljwcjc: "",
        sjjc: "",
        syndwcjc: ""
      };
      this.costdetailListzj = [];
      this.costdetailListsy = [];
    },
    addLedgerClick() {
      if (this.lrForm.id == "" || this.lrForm.id == undefined) {
        this.$refs["lrForm"].validate(valid => {
          if (valid) {
            addLedger({ lrForm: this.lrForm, costList: this.costdetailList }).then(response => {
              this.msgSuccess(response.msg);
              this.addDataVisible = false;
              this.getList();
            });
          }
        });
      } else {
        editLedger(this.lrForm).then(response => {
          this.msgSuccess(response.msg);
          this.addDataVisible = false;
          this.getList();
        });
      }
    },
    editCostClick() {
      editCost({
        costList: [...this.costdetailListzj, ...this.costdetailListsy],
        createTime: this.queryParams.createTime
      }).then(response => {
        this.msgSuccess(response.msg);
        this.addDataVisible = false;
        this.getList();
      });
    },
    handleAddCost() {
      this.reset();
      this.openCost = true;
      this.titleCost = "费用导入";
    },
    //数据下载
    downloadData() {
      var ledgerids = [];
      for (var i = 0; i < this.ledgerList.length; i++) {
        ledgerids.push(this.ledgerList[i].id);
      }
      downloadLedger(this.addDateRange({
        ledgerids: ledgerids,
        pageSize: 1000,
        pageNum: 1
      }, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data));
        var costList = resData.data;
        debugger
        var fileName = "data.csv"; //使用当前时间戳作为文件名
        var columnDelimiter = ","; //列分割符
        var lineDelimiter = "\r\n"; //行分割符
        var keyValue = resData.downloadStr;
        let result = ""; // 最终结果的字符串
        for (var i = 0; i < keyValue.length; i++) {
          result += this.transferred(keyValue[i]) + columnDelimiter;
        }
        result += lineDelimiter;
        for (var i = 0; i < costList.length; i++) {
          for (var j = 0; j < keyValue.length; j++) {
            console.log(costList[i][keyValue[j]]);
            result += this.transferred(costList[i][keyValue[j]] == undefined ? "" : costList[i][keyValue[j]] + "") + columnDelimiter;
          }
          result += lineDelimiter;
        }
        this.downCsvFile(fileName, result);
        // this.total = resData.count;
        this.loading = false;
      });
      // var fileName = "data.csv"; //使用当前时间戳作为文件名
      // var columnDelimiter = ","; //列分割符
      // var lineDelimiter = "\r\n"; //行分割符
      // var keyValue=Object.keys(this.ledgerDict)
      // let result = ""; // 最终结果的字符串
      // for(var i=0;i<keyValue.length;i++){
      //   result +=this.transferred(this.ledgerDict[keyValue[i]]) +columnDelimiter;
      // }
      // result += lineDelimiter;
      // for (var i = 0; i < this.ledgerList.length; i++) {
      //   for(var j=0;j<keyValue.length;j++){
      //     console.log(this.ledgerList[i][keyValue[j]])
      //     result +=this.transferred(this.ledgerList[i][keyValue[j]]==undefined ? '': +this.ledgerList[i][keyValue[j]]+'') +columnDelimiter;
      //   }
      //   result += lineDelimiter;
      // }
      // this.downCsvFile(fileName,result)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$refs.uploadRef.clearFiles();
    },
    /** 数字台账新增 */
    submitForm: function() {
      console.log(this.form);

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this, this.form.id == undefined) {
            addType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            });
          } else {
            editType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitCostForm() {
      this.$refs["formCost"].validate(valid => {
        if (valid) {
          if (this, this.formCost.id == undefined) {
            addTypeCost(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.openCost = false;
              this.getList();
            });
          } else {

          }
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.valNames = selection.map(item => item.formCode);
      this.single = selection.length !== 1;
      this.multiple = selection.length < 2;
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.addDataVisible = true;
      this.isfylr = false;
      this.lrForm = row;
      debugger
      this.sjlrTitle = "数据修改";
      const ids = row.id || this.ids;
      listTypeDetailByTime(this.addDateRange({
        ledgerid: ids,
        createTime: this.queryParams.createTime,
        pageSize: 1000,
        pageNum: 1
      }, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data));
        this.costdetailList = resData.results;
        this.costdetailListzj = [];
        this.costdetailListsy = [];
        for (var k = 0; k < this.costdetailList.length; k++) {
          if (this.costdetailList[k].cost_type == "钻井" || this.costdetailList[k].cost_type == "研究费及管理费") {
            this.costdetailListzj.push(this.costdetailList[k]);
          } else if (this.costdetailList[k].cost_type == "试油") {
            this.costdetailListsy.push(this.costdetailList[k]);
          }
        }
        // this.total = resData.count;
        this.loading = false;
      });
    },
    //费用录入
    handleCostDetail(row) {
      this.addDataVisible = true;
      this.isfylr = true;
      const ids = row.id || this.ids;
      this.lrForm = deepCopy(row);
      this.lrForm.id = "";
      this.sjlrTitle = "数据修改";
      listTypeDetailByTime(this.addDateRange({
        ledgerid: ids,
        createTime: this.queryParams.createTime,
        pageSize: 1000,
        pageNum: 1
      }, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data));
        this.costdetailList = resData.results;
        for (var i = 0; i < this.costdetailList.length; i++) {
          this.costdetailList[i].id = "";
        }
        // this.total = resData.count;
        this.loading = false;
      });
    },
    //批量复制
    handleCopy() {
      copyLedgerData(this.addDateRange({ createTime: this.queryParams.createTime })).then(response => {
        this.msgSuccess("复制成功");
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var ids = [];
      if (row.id != undefined) {
        ids = [row.id];
      } else {
        ids = this.ids;
      }
      this.$confirm("是否确认删除该数据项? 请谨慎操作！", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delType({ id: ids });
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      });
    },
    //添加
    handleCostAdd(row) {
      this.editCostdetail = row;
      this.addCostdetail = true;
    },
    addCostClick() {
      this.editCostdetail.real_cost += Number(this.addCostForm.real_cost);
      this.addCostdetail = false;
    },
    handleCostDelete(row) {
      var _this = this;
      this.$confirm("是否确认删除该数据项? 请谨慎操作！", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        _this.addDataVisible = false;
        return delCostType({ id: [row.id] });
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      });
    },
    // 场景字典翻译
    sceneFormat(row, column) {
      return this.selectDictLabel(this.sceneOptions, row.scene);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids;
      dataEche({ "id": row.id }).then((response) => {
        this.form = JSON.parse(Decrypt(response.data));
        this.open = true;
        this.title = "模板修改";
      });
    },
    /** 文件上传成功调用的钩子函数 */
    handleSuccess(data) {
      this.form.path = data.saveFile;
      this.formCost.path = data.saveFile;
      this.$message.success("文件上传成功！");
      // inspectHeaderAll({ 'path': data.saveFile }).then(response => {
      //   var resData = JSON.parse(Decrypt(response.data))
      //   if (resData.bol) {
      //     this.form.path = data.saveFile
      //     this.$message.success('文件上传成功！');
      //     this.$refs.uploadRef.clearFiles()
      //   } else {
      //     this.onInspect(resData.repeat_values)
      //   }
      // })

    },
    /** 文件上传失败调用的钩子函数 */
    onError() {
      this.form.path = undefined;
      this.$message.error("文件上传失败！");
      this.$refs.uploadRef.clearFiles();
    },
    /** 重复列回显函数 */
    onInspect(data) {
      this.form.path = undefined;
      this.$message.error("文件" + data + "列重复，请检查之后重新上传！");
      this.$refs.uploadRef.clearFiles();
    },
    transferred(data) {
      return data.replace(/<br>/g, "\r\n").replace(/&gt;/g, ">");
    },
    downCsvFile(fileName, result) {
      var fileName = fileName; //使用当前时间戳作为文件名
      var blob = new Blob(["\uFEFF" + result], { type: "text/csv;" }); //记得将编码格式设置一下，避免最终下载的文件出现乱码
      var downloadLink = document.createElement("a");
      if ("download" in downloadLink) {
        var url = URL.createObjectURL(blob);
        downloadLink.href = url;
        downloadLink.download = fileName;
        downloadLink.hidden = true;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      } else {
        if (navigator.msSaveBlob) {
          //IE10+
          navigator.msSaveBlob(blob, fileName);
        }
      }
    },

    handleModelwell() {
      var data = [["统计年度", "区域", "凹陷", "钻机", "型号", "项目组", "井号", "井类型", "是否核销", "开钻日期", "完钻日期", "完井日期", "井深", "累计完成进尺", "设计进尺", "上一年度完成进尺"]];
      //添加到work sheel中
      const ws = XLSX.utils.aoa_to_sheet(data);
      //创建新的work book
      const wb = XLSX.utils.book_new();
      //讲work shell添加到work book中并命名为‘Shell1’
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      //将work book写入文件，并取名为new_excel.xlsx
      XLSX.writeFile(wb, "井数据模板.xlsx");
      // downmodel({fileName:'批复模板.xlsx'}).then(response => {
      //   debugger
      //     var files = JSON.parse(Decrypt(response.data))
      //     this.download(files.path, files.name);

      //   });
    },

    handleModelcost() {
      var data = [["井号", "费用名称", "乙方", "费用", "已结费用", "备注", "费用类型", "年份", "日期"]];
      //添加到work sheel中
      const ws = XLSX.utils.aoa_to_sheet(data);
      //创建新的work book
      const wb = XLSX.utils.book_new();
      //讲work shell添加到work book中并命名为‘Shell1’
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      //将work book写入文件，并取名为new_excel.xlsx
      XLSX.writeFile(wb, "费用模板.xlsx");
      // downmodel({fileName:'批复模板.xlsx'}).then(response => {
      //   debugger
      //     var files = JSON.parse(Decrypt(response.data))
      //     this.download(files.path, files.name);

      //   });
    }
  }
};
</script>

<style scoped>
::v-deep .el-table th.el-table__cell > .cell {
  display: inline-block;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  position: relative;
  vertical-align: middle;
  padding-left: 10px;
  padding-right: 10px;
  width: 100%;
  white-space: nowrap !important;
}

</style>
